package com.example.delivery.controller;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.delivery.pojo.*;
import com.example.delivery.service.AddressService;
import com.example.delivery.service.OrderService;
import com.example.delivery.service.ReviewService;
import com.example.delivery.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private AddressService addressService;
    @Autowired
    private UserService userService;

    @PostMapping("/add")
    @ResponseBody // 确保返回的是 JSON 数据
    public Map<String, Object> add(HttpSession session,@RequestBody OrderResult OrderResult) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 1. 根据地址 ID 查询地址信息
            Address address = addressService.findById(Integer.valueOf(OrderResult.getSelectedAddress()));
            if (address == null) {
                response.put("success", false);
                response.put("message", "地址不存在");
                return response;
            }

            // 2. 从 session 中获取餐厅 ID 和总金额
            String restaurantId = (String) session.getAttribute("restaurantId");
            String totalAmount = (String) session.getAttribute("totalAmount");

            // 3. 构造订单对象
            Order order = new Order();
            order.setOrderNo(IdWorker.getIdStr()); // 生成订单号
            order.setUserId(Math.toIntExact(address.getUserId()));
            order.setContactPhone(address.getMobile());
            order.setCreateTime(new Date());
            order.setDeliveryAddress(address.getAddress());
            order.setRestaurantId(Integer.valueOf(restaurantId));
            order.setPaymentTime(new Date());
            order.setTotalAmount(new BigDecimal(totalAmount));
            order.setStatus(1); // 设置订单状态未评价

            // 4. 创建订单
            Order createdOrder = orderService.createOrder(order);
            if (createdOrder == null) {
                response.put("success", false);
                response.put("message", "订单创建失败");
                return response;
            }

            // 5. 扣款操作
            String username = (String) session.getAttribute("user");
            User user = userService.findByUserName(username);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return response;
            }

            BigDecimal balance = user.getBalance();
            BigDecimal amount = new BigDecimal(totalAmount);
            if (balance.compareTo(amount) < 0) {
                response.put("success", false);
                response.put("message", "余额不足");
                return response;
            }

            user.setBalance(balance.subtract(amount));
            userService.updateUser(user);

            session.setAttribute("currentOrder", createdOrder);

            // 6. 返回成功响应
            response.put("success", true);
            response.put("message", "订单创建成功");
            response.put("order", createdOrder);
            return response;

        } catch (Exception e) {
            // 7. 异常处理
            response.put("success", false);
            response.put("message", "订单创建失败，原因：" + e.getMessage());
            return response;
        }
    }

    /**
     * 查询用户所有的订单
     * @param session
     * @return
     */
    @GetMapping("/all")
    public ModelAndView add(HttpSession session) {
        //获取用户id
        Integer userId = (Integer) session.getAttribute("userId");

        //根据用户id查询所有的订单
        List<Order> orders = orderService.findAllByUserId(userId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("cart");
        modelAndView.addObject("orders", orders);
        return modelAndView;
    }

    @Autowired
    private ReviewService reviewService;
    @PostMapping("/evaluate")
    @ResponseBody
    public Map<String, Object> evaluate(HttpSession session, @RequestBody EvaluateData evaluateData) {
        Map<String, Object> map = new HashMap();
        try{
            // 更新订单状态，更改为已更新
            Order order = orderService.findById(evaluateData.getOrderId());
            order.setStatus(0);
            orderService.updateOrderStatus(order);
            // 新增评价数据
            Review review = new Review();
            review.setContent(evaluateData.getComment());
            review.setRating(Integer.valueOf(evaluateData.getRating()));
            review.setCreateTime(new Date());
            review.setUserId((Integer) session.getAttribute("userId"));
            review.setRestaurantId(order.getRestaurantId());
            reviewService.save(review);
            map.put("success",true);
            map.put("message","评价成功");
        }catch (Exception e) {
            map.put("success",false);
            map.put("message",e.getMessage());
        }
       return map;
    }
}
